<template>
  <div>
    <h2>发布作业</h2>
    <el-form :model="newHomework" ref="homeworkForm" label-width="100px">
      <el-form-item
          label="作业标题"
          prop="title"
          :rules="[{ required: true, message: '请输入作业标题', trigger: 'blur' }]"
      >
        <el-input v-model="newHomework.title" placeholder="请输入作业标题"></el-input>
      </el-form-item>
      <el-form-item
          label="作业内容"
          prop="content"
          :rules="[{ required: true, message: '请输入作业内容', trigger: 'blur' }]"
      >
        <el-input
            type="textarea"
            v-model="newHomework.content"
            rows="4"
            placeholder="请输入作业内容"
        ></el-input>
      </el-form-item>
      <el-form-item
          label="截止日期"
          prop="dueDate"
          :rules="[{ required: true, message: '请选择截止日期', trigger: 'change' }]"
      >
        <el-date-picker
            v-model="newHomework.dueDate"
            type="datetime"
            placeholder="选择截止日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submitHomework">发布</el-button>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { BASE_URL } from "@/config";

export default {
  props: ["course_id"], // 接收从路由传递的课程号
  data() {
    return {
      newHomework: {
        title: "",
        content: "",
        dueDate: null, // 确保初始值为 null 或空字符串
      },
    };
  },
  methods: {
    async submitHomework() {
      try {
        // 验证表单
        const isValid = await this.$refs.homeworkForm.validate();
        if (!isValid) return;

        // 提交作业
        const response = await axios.post(`${BASE_URL}/homework/assign`, {
          title:this.newHomework.title,
          course_id: this.course_id, // 使用传递的 course_id
          content:this.newHomework.content,
          due_date:this.newHomework.dueDate,
        });

        if (response.data && response.data.code === 200) {
          this.$message.success("作业发布成功！");
          this.$router.push({ name: "CourseDetail", query: { course_id: this.course_id } }); // 返回课程详情页面
        } else {
          this.$message.error("作业发布失败，请重试！");
        }
      } catch (error) {

      }
    },
    cancel() {
      // 取消操作，返回上一页
      this.$router.push({ name: "CourseDetail", query: { course_id: this.course_id } });
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
